<?php
/**
 * brand.php
 *
 * Created on 2014-12-26
 * Create by LDD
 */
namespace haibao\cms\data;

use haibao\cms\model\data\BrandProperty;
use \haibao\cms\model\filter\Brand as BrandFilter;
use \haibao\cms\model\filter\BrandType as BrandTypeFilter;
use \haibao\cms\model\filter\BrandProperty as BrandPropertyFilter;
use haibao\frame\data\query\Condition;

class Brand extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\Brand');
	}

	
	/**
	 * @parma \haibao\cms\model\filter\Brand $brandFilter;
	 */
	public function getAll($brandFilter){
        return parent::getAll($brandFilter);
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function add($model){
		
		$this->beginTranscation();
		try{
			parent::add($model);
 			$this->addBrandProperty($model);
			$this->addBrandType($model);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
//		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
//			$oldId = $this->addOldBrandLibrary($model);
//			$this->addDataMigrationMap($model,$oldId);
//		}
	}
	
	/**
	 * 通过品牌ID获取粉丝数 EditFansNum
	 * @param string $brandId 品牌ID
	 * @param string $type 类型 点击量：\haibao\cms\model\data\Brand::TYPE_CLICKNUM 粉丝数：\haibao\cms\model\data\Brand::TYPE_FANSNUM
	 */
	public function getEditFansNumByBrandId($brandId,$type){
		$result = array();
		if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
			$sql = 'select EditFansNum from BrandStatisticalInfo where BrandId = %s';
		}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
			$sql = 'select EditClickNum from BrandStatisticalInfo where BrandId = %s';
		}
		$result = $this->query($sql,array($brandId))->fetch_assoc();
		return $result;
	}
	
	/**
	 * 修改粉丝数 EditFansNum
	 * @param string $editFansNum 粉丝数/点击量
	 * @param string $brandId 品牌ID
	 * @param string $type
	 */
	public function editFansNumByBrandId($editFansNum,$brandId,$type){
		if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
			$sql = 'update BrandStatisticalInfo set EditFansNum = %s where BrandId = %s';
		}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
			$sql = 'update BrandStatisticalInfo set EditClickNum = %s where BrandId = %s';
		}
		$this->query($sql,array($editFansNum,$brandId));
	}	
	
	/**
	 * 其他模块调用添加品牌
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function addBrandForOther($model,$syncOld = true){
	
		$this->beginTranscation();
		try{
			parent::add($model);
			$this->addBrandStatisticalInfo($model->Id);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
        if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
            if($syncOld){
			    $oldId = $this->addOldBrandLibrary($model);
                $this->addDataMigrationMap($model,$oldId);
            }
        }
        return  $model->Id;
    }
	/**
	 * 通过品牌Id查找品牌
	 */
	public function getBrandById($brandIds,$isLock = false){
		$isOneModel = true;
		if(is_array($brandIds)){
			$isOneModel = false;
		} else {
			$brandIds = array($brandIds);
		}
		$brandFilter = new BrandFilter();
		$brandTypeFilter = new BrandTypeFilter();
		$brandPropertyFilter = new BrandPropertyFilter();
		$brandFilter->select(array(
		        BrandFilter::CONDITION_FIELD_NAME_ID,
				BrandFilter::CONDITION_FIELD_NAEM_ISHOT,
				BrandFilter::CONDITION_FIELD_NAEM_ISRECOMMEND,
				BrandFilter::CONDITION_FIELD_NAEM_STORY,
				BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_TIME,
				BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_NATION,
				BrandFilter::CONDITION_FIELD_NAME_IMGID,
				BrandFilter::CONDITION_FIELD_NAME_BRANDREGION,
				BrandFilter::CONDITION_FIELD_NAME_BUYTYPE,
				BrandFilter::CONDITION_FIELD_NAME_CURDESIGNER,
				BrandFilter::CONDITION_FIELD_NAME_DESCRIPTION,
				BrandFilter::CONDITION_FIELD_NAME_FOUNDER,
				BrandFilter::CONDITION_FIELD_NAME_ID,
				BrandFilter::CONDITION_FIELD_NAME_TAG_ID,
				BrandFilter::CONDITION_FIELD_NAME_NAMECN,
				BrandFilter::CONDITION_FIELD_NAME_NAMEEN,
				BrandFilter::CONDITION_FIELD_NAME_ANOTHERNAME,
				BrandFilter::CONDITION_FIELD_NAME_STATUS,
				BrandFilter::CONDITION_FIELD_NAME_PARENT_BRAND_ID
				));
		$brandPropertyFilter->select(array(
				BrandPropertyFilter::CONDITION_FIELD_NAME_PROPERTY,
				BrandPropertyFilter::CONDITION_FIELD_NAME_BRAND_ID
				));
		$brandTypeFilter->select(array(
				BrandTypeFilter::CONDITION_FIELD_NAME_BRAND_ID,
				BrandTypeFilter::CONDITION_FIELD_NAME_TYPE
				));
		$brandFilter->leftJoin($brandPropertyFilter,null,BrandFilter::CONDITION_FIELD_NAME_ID,BrandPropertyFilter::CONDITION_FIELD_NAME_BRAND_ID,BrandFilter::CONDITION_FIELD_NAME_BRAND_PROPERTY);
		$brandFilter->leftJoin($brandTypeFilter,null,BrandFilter::CONDITION_FIELD_NAME_ID,BrandTypeFilter::CONDITION_FIELD_NAME_BRAND_ID,BrandFilter::CONDITION_FIELD_NAME_BRAND_TYPE);
		
		$brandFilter->where(BrandFilter::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_IN, $brandIds);
		if(!$isLock){
			$brandFilter->where(BrandFilter::CONDITION_FIELD_NAME_STATUS, \haibao\frame\data\query\Condition::CONDITION_EQUAL, \haibao\cms\model\data\Brand::STATUS_ENABLE);
		}
		$brandModel = null;
		if($isOneModel){
			$brandModel = $this->getOne($brandFilter);
		} else {
			$brandModel = $this->getAll($brandFilter);
		}
		return $brandModel;
	}
	/**
	 * 创建设计师的空间
	 */
	public function createDesignerSpace($brandModel){
		parent::add($brandModel);
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->createOldDesignerSpace();
			$this->addDataMigrationMap($brandModel,$oldId);
		}
	}
	/**
	 * 通过tagId删除品牌
	 */
	public function deleteBrandByTagId($tagId,$filter){
		parent::update(array(
				\haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_STATUS=>\haibao\cms\model\data\Brand::STATUS_DISABLE),
				 $filter);
		$this->delAllBrandIdByWeight();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$this->deleteOldBrandLibraryByTagId($tagId);
		}
	}
	private function deleteOldBrandLibraryByTagId($tagId){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$sql ="update `library_brand` set status =0 where tag_id= %s";
		$this->query($sql,array($tagId));
	}
	/**
	 * 通过tagId删除设计师空间
	 */
	public function deletecDesignerSpaceByTagId($tagId,$filter){
		parent::remove($filter);
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql ="delete from `library_brand` where tag_id= %s";
			$this->query($sql,array($tagId));
		}
	}
	/**
	 * 根据标签ID更新品牌信息
	 * @param : Array $arrSet
	 * @param : Object \haibao\cms\model\filter\Brand $filter
	 * @param : Object \haibao\cms\model\data\Brand $model
	 */
	public function updateBrandByFilter($arrSet,$filter,$model = null){

		$this->beginTranscation();
		try{
			$this->update($arrSet,$filter);
			$this->delAllBrandIdByWeight();
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->updateOldBrandLibrary($model,false);
		}
	}
	
	public function updateCommentNum($brandId,$userId,$num = 1,$isSub=false){
		if ($isSub){
			$sql = 'update BrandStatisticalInfo set CommentsNum=CommentsNum-'.$num.' where BrandId=%s';
		}else {
			$sql = 'update BrandStatisticalInfo set CommentsNum=CommentsNum+'.$num.' where BrandId=%s';
			
			$additionalSql = "insert into BrandAttentionRecord(BrandId,UserId,CreateTime,RecordType) value(%s,%s,%s,%s)";
			$this->query($additionalSql,array($brandId,$userId,date('Y-m-d H:i:s'),\haibao\cms\model\data\BrandAttentionRecord::RECORD_TYPE_COMMENT));
		}
		$this->query($sql,array($brandId));
	}
	
	/**
	 * 创建老设计师空间
	 */
	private function createOldDesignerSpace(){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
	
		$sql = "insert into  `library_brand` (`tag_id` ,`name_ch` ,`name_en` ,`date`,`tag_type`) (
		select A.tag_id ,A.tag_name,A.tag_name,%s,A.tag_type
		from tag as A
		where A.parent_id = %s and A.tag_type=%s and A.tag_id not in
		(
		select tag_id from library_brand
		)
		)";
		$this->query($sql,array(new \DateTime(),\haibao\cms\model\data\Tag::DESINGER_TAG_ID,\haibao\cms\model\data\Tag::TYPE_DESIGNER));
		return $this->getDb()->insert_id;
	}
	/**
	 * 添加老品牌数据
	 */
	private function addOldBrandLibrary($model){
		$avatar = '';
		if($model->ImgId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$avatar = $imageData->getImageUrl($model->ImgId);
			$avatar = ltrim($avatar, '/');
		}
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$brandTime = '0000-00-00';
		if($model->BrandCreateTime){
			$brandTime = $model->BrandCreateTime;
		}
		$place = 0;
		if(!empty($model->BrandRegion)){
			$place = (int)$model->BrandRegion;
		}
		$sql = "INSERT INTO `library_brand` (`tag_id`, `desc`,`avatar` ,`name_ch`,`name_en`,`pdtypes`,`place`,
											`pinyin_ch`,`pinyin_en` ,`status` ,`date`,`ad_name`,`ad_url`,
											 `brand_time`, `address`, `founder`, `cur_designer`,`story`,`buy_type`,`is_hot`,
											 `is_tuijian`, `tag_type`, `update`)
                VALUES (%s,%s,%s, %s, %s, %s, %s, %s,%s, %s, %s,%s,%s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s)";
		$insertArr = array($model->TagId,$model->Description, $avatar, $model->NameCN, $model->NameEN, 
					$model->Btypes,$place, $model->PinyinCN, $model->PinyinEN,
					$model->Status, new \DateTime(),$model->AdName,$model->AdUrl, $brandTime, 
					$model->BrandCreateNation, $model->Founder,$model->CurDesigner,$model->Story,$model->BuyType,
				    $model->IsHot,$model->IsRecommend, $model->TagType, $model->UpdateTime);
		$this->query($sql,$insertArr);
		$brandId = $this->getDb()->insert_id;
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "INSERT INTO `brand_pdtype` (`bid`, `pdtypeid`) values";
			foreach ($model->BrandType as $key=>$type) {
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$brandId);
				array_push($arrValues,$type);	
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into `brand_property`(`bid`, `property`) values";
			foreach($model->BrandProperty as $property){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$brandId);
				array_push($arrValues,$property);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		return $brandId;
	}
	private function addDataMigrationMap($model,$oldId){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldId));
	}
	/**
	 * @param int $tagId
	 */
	public function updateLastModified($tagId){
		
		$tagData = new \haibao\cms\data\Tag();
		$tagData->updateById($tagId, array(\haibao\cms\model\filter\Tag::CONDITION_FIELD_NAME_LASTMODIFIED=>time()));
	}
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function addBrandProperty($model){
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
				$sql = "insert into BrandProperty(BrandId,Property) values";
				foreach($model->BrandProperty as $property){
					array_push($arrSql,'(%s,%s)');
					array_push($arrValues,$model->Id);
					array_push($arrValues,$property);
				}
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
		}
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function save($model){
		$this->beginTranscation();
		try{
			$arrSet = array(
					BrandFilter::CONDITION_FIELD_NAEM_ISHOT =>$model->IsHot,
					BrandFilter::CONDITION_FIELD_NAEM_ISRECOMMEND =>$model->IsRecommend,
					BrandFilter::CONDITION_FIELD_NAME_TAG_ID =>$model->TagId,
					BrandFilter::CONDITION_FIELD_NAEM_STORY =>$model->Story,
					BrandFilter::CONDITION_FIELD_NAME_IMGID =>$model->ImgId,
					BrandFilter::CONDITION_FIELD_NAEM_UPDATE_TIME =>$model->UpdateTime,
					BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_NATION =>$model->BrandCreateNation,
					BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_TIME =>$model->BrandCreateTime,
					BrandFilter::CONDITION_FIELD_NAME_CURDESIGNER =>$model->CurDesigner,
					BrandFilter::CONDITION_FIELD_NAME_DESCRIPTION =>$model->Description,
					BrandFilter::CONDITION_FIELD_NAME_FOUNDER =>$model->Founder,
					BrandFilter::CONDITION_FIELD_NAME_LASTEDITEBY =>$model->LastEditeBy,
					BrandFilter::CONDITION_FIELD_NAME_NAMECN =>$model->NameCN,
					BrandFilter::CONDITION_FIELD_NAME_NAMEEN =>$model->NameEN,
					BrandFilter::CONDITION_FIELD_NAEM_PINYIN_CN =>$model->PinyinCN,
					BrandFilter::CONDITION_FIELD_NAEM_PINYIN_EN =>$model->PinyinEN,
					BrandFilter::CONDITION_FIELD_NAME_ANOTHERNAME =>$model->AnotherName,
					BrandFilter::CONDITION_FIELD_NAEM_BTYPES =>$model->Btypes,
					BrandFilter::CONDITION_FIELD_NAME_BRANDREGION =>$model->BrandRegion,
					BrandFilter::CONDITION_FIELD_NAME_BUYTYPE =>$model->BuyType,
			        BrandFilter::CONDITION_FIELD_NAME_STATUS =>$model->Status,
			        BrandFilter::CONDITION_FIELD_NAME_PARENT_BRAND_ID =>$model->ParentBrandId
					);
			parent::updateById($model->Id, $arrSet);
			$delSql = "delete from BrandProperty where BrandId =%s";
			$this->query($delSql,array($model->Id));
			$this->addBrandProperty($model);
			$delSql = "delete from BrandType where BrandId =%s";
			$this->query($delSql,array($model->Id));
			$this->addBrandType($model);
			$starDefineData = new \haibao\cms\data\star\StarDefine();
			$starDefineData->addStarSecret($model->Id,$model->StarSecret);
			$starDefineData->addStarBroker($model->Id,$model->StarBroker);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->updateOldBrandLibrary($model);
		}
	}
	/**
	 * 删除品牌
	 */
	public function deleteBrandById($brandId,$status = \haibao\cms\model\data\Brand::STATUS_DISABLE){
		parent::updateById($brandId,array('Status'=>$status));
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$this->deleteOldBrandLibrary($brandId,$status);
		}
		
		$this->delAllBrandIdByWeight();
	}
	
	/**
	 * 根据品牌ID查询相关属性数量
	 */
	public function getBrandStatisticalInfo($brandId){
		$model = null;
		$result = $this->query("select * from BrandStatisticalInfo where BrandId=%s", array(
			$brandId
		));
		while ($result->fetch_assoc()){
			$model = new \haibao\cms\model\data\BrandStatisticalInfo();
			foreach($model->getKeyMap() as $keyName=>$keyType){
				if (!($keyType instanceof \haibao\frame\data\datafield\RelationOneField || $keyType instanceof \haibao\frame\data\datafield\RelationManyField)){
					$model->$keyName = $result->getData($keyType->getFieldName());
				}
			}
		}
		return $model;
	}
	
	public function getBrandOldIdById($id){
		$oldId = $this->getDataMigration('Brand', $id);
		return $oldId;
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	private function addBrandType($model){
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into BrandType(BrandId,Type) values";
			foreach($model->BrandType as $type){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$model->Id);
				array_push($arrValues,$type);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
	
	private function deleteOldBrandLibrary($brandId,$status){
		$oldId = $this->getDataMigration('Brand',$brandId);
		
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$sql ="update `library_brand` set status =%s where id= %s";
		$this->query($sql,array($status,$oldId));
	}
	
	/**
	 *
	 * @param string $tableName
	 * @param int $newPrimaryKey
	 */
	private function getDataMigration($tableName,$newPrimaryKey){
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}
	private function updateOldBrandLibrary($model,$isSave = true){
		$oldId = $this->getDataMigration('Brand',$model->Id);
		if(!$oldId){
			if($model->TagId){
				$oldId = $this->addOldBrandLibrary($model);
				$this->addDataMigrationMap($model,$oldId);
			}
		}
		
		if(empty($oldId)){
			return;
		}
		
		$avatar = '';
		if($model->ImgId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$avatar = $imageData->getImageUrl($model->ImgId);
			$avatar = ltrim($avatar, '/');
		}
		
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$place = 0;
		if(!empty($model->BrandRegion)){
			$place = (int)$model->BrandRegion;
		}
		if($isSave){
			$sql ="UPDATE `library_brand` SET  `tag_id` = %s,`desc` = %s, `avatar` = %s,`name_ch` = %s,`name_en` = %s,`pdtypes`=%s,`place` = %s,`pinyin_ch` = %s,`pinyin_en` = %s,`brand_time` = %s,
		      `address` = %s,`founder`= %s,`cur_designer` = %s,`story`= %s, `buy_type` = %s,`is_hot` = %s, `is_tuijian` = %s, `tag_type`=%s, `update` = %s WHERE `id` =%s";
			$updateArr = array($model->TagId,$model->Description, $avatar, $model->NameCN, $model->NameEN,
					$model->Btypes,$place, $model->PinyinCN, $model->PinyinEN,$model->BrandCreateTime , $model->BrandCreateNation, $model->Founder, $model->CurDesigner,$model->Story,$model->BuyType,$model->IsHot,$model->IsRecommend,$model->TagType,$model->UpdateTime,$oldId);
			$this->query($sql,$updateArr);
		} else {
			$sql ="UPDATE `library_brand` SET  `name_ch` = %s,`name_en` = %s,`tag_type`=%s, `update` = %s WHERE `id` =%s";
			$updateArr = array($model->NameCN, $model->NameEN,$model->TagType,$model->UpdateTime,$oldId);
			$this->query($sql,$updateArr);
		}
		
		$delSql = "delete from `brand_pdtype` where `bid` =%s";
		$this->query($delSql,array($oldId));
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "INSERT INTO `brand_pdtype` (`bid`, `pdtypeid`) values";
			foreach ($model->BrandType as $key=>$type) {
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$oldId);
				array_push($arrValues,$type);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		$delSql = "delete from `brand_property` where `bid` =%s";
		$this->query($delSql,array($oldId));
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into `brand_property`(`bid`, `property`) values";
			foreach($model->BrandProperty as $property){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$oldId);
				array_push($arrValues,$property);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
	
	public function getStarPkBandById($BrandId){
	    $brandFilter = new BrandFilter();
	    $brandFilter->select(array(
	        BrandFilter::CONDITION_FIELD_NAME_ID,
	        BrandFilter::CONDITION_FIELD_NAME_TAG_ID,
	        BrandFilter::CONDITION_FIELD_NAME_NAMECN,
	        BrandFilter::CONDITION_FIELD_NAME_NAMEEN,
	    ));
	    $brandFilter->where( BrandFilter::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_EQUAL, $BrandId);
	    $brandModel = $this->getOne($brandFilter);
	
	    return $brandModel;
	
	}
	
	public function getAllBrandIdByWeight(){
		$cache = new \haibao\cms\cache\Brands();
		$arrBrandId = $cache->getBrandsCacheData();
		if(!$arrBrandId){
			$arrBrandId = array();
			$arrBrandInfo = array();
			$arrTagId = array();
			$sql = 'select b.Id,b.TagId from Brand as b left join BrandStatisticalInfo as s on b.Id = s.BrandId where b.Status=%s order by s.WeightCount desc';
			$result = $this->query($sql,array(\haibao\cms\model\data\Brand::STATUS_ENABLE));
			while ($result->fetch_assoc()){
				$arrTagId[] = $result->getData('TagId');
				$arrBrandInfo[$result->getData('Id')] = $result->getData('TagId');
			}
			
			$data = new \haibao\cms\data\Tag();
			$topPicIds = $data->getTopicIdByTagId($arrTagId);
			foreach($arrBrandInfo as $brandId=>$brandTagId){
				if(isset($topPicIds[$brandTagId]) && $topPicIds[$brandTagId]){
					$arrBrandId[] = $brandId;
				}
			}
			
			$cache->setBrandsCacheData($arrBrandId);
		}
		return $arrBrandId;
	}
	
	public function addBrandClickNum($brandId){
		$sql = 'update BrandStatisticalInfo set ClickNum=ClickNum+1,EditClickNum=EditClickNum+1 where BrandId=%s';
		$result  = $this->query($sql,array($brandId));
	}
	
	public function getBrandShowInfo($eventCategoryId,$starDate){
		$arrBrandShowInfo = array();
		$sql = "SELECT
					a.PublishId,
					b.BrandTagId,
					ed.Id,
					ed.EventName,
					t.ParentId
				FROM
					EventArticle AS e
				LEFT JOIN InformationBrand AS b ON e.ArticleId = b.InfoId
				LEFT JOIN Article AS a ON e.ArticleId = a.Id
				LEFT JOIN ArticleTag t ON e.ArticleId = t.ArticleId 
				LEFT JOIN EventDefine as ed ON e.EventId = ed.Id
				WHERE
					ed.StartDate >= %s AND
					b.InfoType = %s and
		            t.TagId = 324
				AND e.EventId IN (
					SELECT
						ec.EventId
					FROM
						EventCategory as ec LEFT JOIN EventCategoryDefine as ecd ON ec.CategoryId = ecd.Id
					WHERE
				    ecd.ParentId=%s
				)
				ORDER BY a.PublishTime DESC";
		$result  = $this->query($sql,array($starDate,1,$eventCategoryId));
		while ($row = $result->fetch_assoc()){
			$arrBrandShowInfo[] = $row;
		}
		return $arrBrandShowInfo;
	}
	
	public function getBrandProperty($brandId){
		$brandId = (array)$brandId;
		$brandPropertyArr = array();
		$brandStr = preg_replace('/\d+/', '%s', implode(',',$brandId));
		$result = $this->query("select BrandId,EditFansNum,ClickNum,EditClickNum from BrandStatisticalInfo where BrandId in ($brandStr)", $brandId);
		while ($result->fetch_assoc()){
			$temp = array();
			$temp['FansNum'] = $result->getData('EditFansNum');
			$temp['ClickNum'] = $result->getData('ClickNum');
			$temp['EditClickNum'] = $result->getData('EditClickNum');
			$brandPropertyArr[$result->getData('BrandId')] = $temp;
		}
		return $brandPropertyArr;
	}
	
	private function delAllBrandIdByWeight(){
		$cache = new \haibao\cms\cache\Brands();
		$cache->delBrandsCacheData();
	}
	
	private function addBrandStatisticalInfo($brandId){
	    $sql = 'insert into BrandStatisticalInfo(`BrandId`) values(%s)';
	    $this->query($sql,array($brandId));
	}
	
	public function getLibraryBrandRecommend(){
	    $sql = 'SELECT
                	BrandTagId
                FROM
                	(
                		SELECT
                			BrandTagId,
                			PublishTime
                		FROM
                			InformationBrand
                		WHERE
                			IsPrimaiy = 1
                		ORDER BY
                			PublishTime DESC
                		LIMIT 20
                	) AS c
                GROUP BY
                	c.BrandTagId
                ORDER BY
                	PublishTime DESC
                LIMIT 12';
	    $brandResult = $this->query($sql);
	    $brandIdArr = array();
	    while($row = $brandResult->fetch_assoc()){
	        $brandIdArr[] = $row['BrandTagId'];
	    }
	    return $brandIdArr;
	}
	
	public function getBrandIdByInfoId($articleId,$imagecollId){
	    $articleBrand = $imagecollBrand = array();
	    if($articleId){
	        $articleStr = preg_replace('/\d+/','%s',implode(',',$articleId));
	        $sql = 'select BrandTagId from InformationBrand where InfoId in ('.$articleStr.') and InfoType = 1 and IsPrimaiy = 1';
	        $articleResult = $this->query($sql,$articleId);
	        while($row = $articleResult->fetch_assoc()){
	            $articleBrand[] = $row['BrandTagId'];
	        }
	    }
	    if($imagecollId){
	        $imagecollStr = preg_replace('/\d+/','%s',implode(',',$imagecollId));
	        $sql = 'select BrandTagId from InformationBrand where InfoId in ('.$imagecollStr.') and InfoType = 2 and IsPrimaiy = 1';
	        $imagecollResult = $this->query($sql,$imagecollId);
	        while($row = $imagecollResult->fetch_assoc()){
	            $imagecollBrand[] = $row['BrandTagId'];
	        }
	    }
	    $brandTagIds = array_merge($articleBrand,$imagecollBrand);
	    $brandTagInfo = \haibao\cms\business\Tag::getTagsById($brandTagIds);
	    foreach($brandTagInfo as $key=>$temp){
            if($temp['TagType'] == 1){
                $brandTagInfo[$key]['tagUrl'] = '/brands/'.$temp['Id'].'/';
            }elseif($temp['TagType'] == 4){
                $brandTagInfo[$key]['tagUrl'] = '/stars/'.$temp['Id'].'/';
            }else{
                $brandTagInfo[$key]['tagUrl'] = preg_replace('/\/(.*?)\/(.*)/i', '/${1}/'.$temp['Id'].'/', $temp['Url']);
            }
	    }
	    return $brandTagInfo;
	}
	
	public function getBrandLookBookByName($name){
	    if(!empty($name)){
	        $sql = 'SELECT
                	a.NameCN
                FROM
                	Brand AS a
                LEFT JOIN ImageTag AS b ON a.TagId = b.TagId
                WHERE
                	a.`Status` = 1
                AND  b.ImageId in (select ImageId from ImageTag where TagId  = 5998)
	            AND a.NameCN like "%'.$name.'%"
                GROUP BY a.TagId';
	        $result = $this->query($sql);
	        $brandName = array();
	        while($row = $result->fetch_assoc()){
	            $brandName[] = $row['NameCN'];
	        }
	    }else{
	        $cache = new \haibao\cms\cache\Brands();
	        $brandName = $cache->getBrandLookBookCacheData();
	        if(empty($brandName)){
	            $sql = 'SELECT
                	a.NameCN
                FROM
                	Brand AS a
                LEFT JOIN ImageTag AS b ON a.TagId = b.TagId
                WHERE
                	a.`Status` = 1
                AND  b.ImageId in (select ImageId from ImageTag where TagId  = 5998)
                GROUP BY a.TagId';
	            $result = $this->query($sql);
	            $brandName = array();
	            while($row = $result->fetch_assoc()){
	                $brandName[] = $row['NameCN'];
	            }
	            $cache->setBrandLookBookCacheData($brandName);
	        }
	    }
	    return $brandName;
	}
}
